//
//  ViewController.m
//  CoreDataAddressBook
//
//  Created by WangZe on 15/11/21.
//  Copyright © 2015年 王泽龙. All rights reserved.
//

#import "ViewController.h"
#import "Contact.h"
#import "WZLCoreData.h"
#import "pinyin.h"
#import "POAPinyin.h"
#import "AddViewController.h"
@interface ViewController ()<UITableViewDataSource, UITableViewDelegate>
@property(nonatomic, retain) UITableView *tableView;
@property(nonatomic, retain) NSMutableArray *dataArr;
@property(nonatomic, retain) WZLCoreData *manager;
@property(nonatomic, retain) NSMutableDictionary *sectionDic;
@property(nonatomic, retain) NSArray *contactArr;
@property(nonatomic, retain) NSMutableArray *detailArr;

@end

@implementation ViewController
- (void)viewWillAppear:(BOOL)animated
{
    self.detailArr = [NSMutableArray array];
    // 获得查询数据的请求,相当于数据库的查询语句
    NSFetchRequest *request = [[NSFetchRequest alloc] initWithEntityName:@"Contact"];
    NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"name" ascending:YES];
    
    [request setSortDescriptors:[NSArray arrayWithObjects:sortDescriptor, nil]];
    
    NSError *error;
    
    self.contactArr = [self.manager.managedObjectContext executeFetchRequest:request error:&error];
    
    //    NSLog(@"~~~~~~~%@", self.contactArr);
    
    if (self.contactArr.count != 0) {
        for (int i = 0; i < 26; i++)
        {
            [self.sectionDic setObject:[NSMutableArray array] forKey:[NSString stringWithFormat:@"%c",'A'+i]];
            NSMutableArray *arr = [NSMutableArray array];
            for (Contact *temp in self.contactArr) {
                
                NSString *str = [POAPinyin quickConvert:temp.name];
                NSString *nameStr = [str substringToIndex:1];
                if ([nameStr isEqualToString:[NSString stringWithFormat:@"%c",'A'+i]]) {
                    [arr addObject:temp];
                    [self.sectionDic setObject:arr forKey:[NSString stringWithFormat:@"%c",'A'+i]];
                }
            }
        }
        [self.sectionDic setObject:[NSMutableArray array] forKey:[NSString stringWithFormat:@"%c",'#']];
    }
    else
    {
        for (int i = 0; i < 26; i++)
        {
            [self.sectionDic setObject:[NSMutableArray array] forKey:[NSString stringWithFormat:@"%c",'A'+i]];
        }
        [self.sectionDic setObject:[NSMutableArray array] forKey:[NSString stringWithFormat:@"%c",'#']];
    }
    
    
    [self.tableView reloadData];
}


- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    self.title = @"通讯录";
    self.sectionDic = [[NSMutableDictionary alloc] init];
    [self createView];
    self.manager = [WZLCoreData shareWZLCoreDataManager];
    NSLog(@"url == %@", [self.manager applicationDocumentsDirectory]);

}

- (void)createView
{
    self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height) style:UITableViewStylePlain];
    [self.view addSubview:self.tableView];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    [self.tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:@"reuse"];
    
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"添加" style:UIBarButtonItemStylePlain target:self action:@selector(addAction:)];
}
- (void)addAction:(UIBarButtonItem *)button
{
    
    
    UIStoryboard *st = [UIStoryboard storyboardWithName:@"Main" bundle:[NSBundle mainBundle]];
    
    AddViewController *VC = (AddViewController *)[st instantiateViewControllerWithIdentifier:@"AddViewController"];
    
    
//    AddViewController *VC = [[AddViewController alloc] init];
    [self.navigationController pushViewController:VC animated:YES];
    
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return self.sectionDic.count;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
        NSString *key=[NSString stringWithFormat:@"%c",[ALPHA characterAtIndex:section]];
        return  [[self.sectionDic objectForKey:key] count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"reuse" forIndexPath:indexPath];
    NSString *key=[NSString stringWithFormat:@"%c",[ALPHA characterAtIndex:indexPath.section]];
  
    NSMutableArray *persons=[self.sectionDic objectForKey:key];
    if (persons.count != 0) {
        Contact *tact = persons[indexPath.row];
        cell.textLabel.text = tact.name;
    }
    return cell;
}
#pragma mark tableView上的索引
- (NSArray<NSString *> *)sectionIndexTitlesForTableView:(UITableView *)tableView
{
    if ([tableView isEqual:self.tableView]) {
        NSMutableArray *indices = [NSMutableArray arrayWithObject:UITableViewIndexSearch];
        for (int i = 0; i < 27; i++)
            [indices addObject:[[ALPHA substringFromIndex:i] substringToIndex:1]];
        return indices;
    }
    return nil;
}

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{

    NSString *key=[NSString stringWithFormat:@"%c",[ALPHA characterAtIndex:section]];
    if ([[self.sectionDic objectForKey:key] count] !=0) {
       
        return key;
    }
    return nil;
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
